<?php

Yii::import('User.models.User');
/**
 * This is the model class for table "page_revision".
 */
require_once(dirname(__FILE__).'/base/PageRevisionBase.php');
class PageRevision extends PageRevisionBase
{
    public $siteName;
    public $workflow_id;
    
    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        return array(
            array('template_content_id', 'required'),
            array('id, page_id, image, status, creation_datetime, last_update, created_by, updated_by, log, template_content_id, css_files, js_files', 'safe'),
            array('seo_title', 'length', 'max' => 500),
            array('id, creation_datetime, last_update, created_by, updated_by, log, page_id, image, template_content_id, css_files, js_files, status, siteName', 'safe', 'on'=>'search'),
        );
    }
    public function behaviors()
    {
        return array(
            'timestamp'=>array(
                'class'=>'TimestampBehavior',
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        return array(
            'page'=>array(self::BELONGS_TO, 'Page', 'page_id'),
            'createdBy'=>array(self::BELONGS_TO, 'User', 'created_by'),
            'updatedBy'=>array(self::BELONGS_TO, 'User', 'updated_by'),
            'workflows' => array(self::MANY_MANY, 'Workflow', 'page_current_revision(revision, page_id, workflow_id)'),
            'templateContent' => array(self::BELONGS_TO, 'TemplateContent', 'template_content_id'),
        );
    }
    
    protected function beforeValidate()
    {
        if ($this->getIsNewRecord())
            $this->created_by = Yii::app()->user->id;
        else
            $this->updated_by = Yii::app()->user->id;
        
        if (!is_array($this->js_files))
            $this->js_files = array();
        if (count($this->js_files))
        {
            //remove duplicate files
            array_unique($this->js_files);
            $files = array();
            foreach ($this->js_files as $index => $value)
                if (empty($value) === false)
//                    $files[] = str_replace('themes/'.Yii::app()->theme->name.'/scripts/', '', $value);
                    $files[] = basename($value);
            $this->js_files = $files;
        }
        $this->js_files = var_export($this->js_files, true);
        
        if (!is_array($this->css_files))
            $this->css_files = array();
        if (count($this->css_files))
        {
            //remove duplicate files
            array_unique($this->css_files);
            $files = array();
            foreach ($this->css_files as $index => $value)
                if (empty($value) === false)
//                    $files[] = str_replace('themes/'.Yii::app()->theme->name.'/styles/', '', $value);
                    $files[] = basename($value);
            $this->css_files = $files;
        }
        $this->css_files = var_export($this->css_files, true);
        
        return parent::beforeValidate();
    }
    
    protected function afterFind()
    {
        if (empty($this->js_files) === false)
            $this->js_files = $this->evaluateExpression($this->js_files);
        if (empty($this->css_files) === false)
            $this->css_files = $this->evaluateExpression($this->css_files);
        parent::afterFind();
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search($activeWorkflow=false)
    {
        $criteria=new CDbCriteria;
        $keyAttribute = null;
        if ($activeWorkflow)
        {
            $criteria->select = '"t".*, "pcr".workflow_id as workflow_id';
            $keyAttribute = 'workflow_id';
            $criteria->join = 'INNER JOIN '.SITE_TABLE_PREFIX.'page_current_revision pcr ON "pcr".page_id = "t".page_id AND "pcr".revision = "t".id';
        }
        else
        {
            $criteria->with = array(
                'updatedBy'=>array('select'=>'username'), 
                'createdBy'=>array('select'=>'username'), 
                "templateContent"=>array('select'=>'template_id, revision_id', 'with'=>array('template'=>array('select'=>'name'))),
            );
            $criteria->addSearchCondition('"createdBy"."username"',$this->created_by, true, 'AND', 'LIKE');
            $criteria->addSearchCondition('"updatedBy"."username"',$this->updated_by, true, 'AND', 'LIKE');
            $criteria->addSearchCondition('"template".name',$this->template_content_id, true, 'AND', 'LIKE');
            $criteria->addSearchCondition('t.log',$this->log, true, 'AND', 'LIKE');
            $criteria->compare('"t".id',$this->id);
        }
        $criteria->compare('"t".page_id',$this->page_id);

        $config = array(
            'criteria'=>$criteria,
            'sort'=>array(
                'defaultOrder'=>'"t".id DESC, "t".creation_datetime DESC',
            ),
            'pagination'=>array(
                'pageSize'=>Settings::BO_PAGE_SIZE,
            ),
        );
        if (!is_null($keyAttribute))
            $config['keyAttribute'] = $keyAttribute;
        return new CActiveDataProvider(get_class($this), $config);
    }
    
    public function getActiveWorkflows()
    {
        $data = array();
        Yii::trace('Find active workflow');
        //$workflows = $this->workflows();
        $criteria = new CDbCriteria();
        $criteria->join = 'INNER JOIN '.SITE_TABLE_PREFIX.'page_current_revision pcr ON pcr.workflow_id = t.id';
        $criteria->compare('pcr.page_id', $this->page_id);
        $criteria->compare('pcr.revision', $this->id);
        $workflows = Workflow::model()->findAll($criteria);
        Yii::trace('count: '.count($workflows));
        if (count($workflows))
            $data = CHtml::listData($workflows, 'id', 'name');
        Yii::trace('$data: '.CVarDumper::dumpAsString($data));
        return $data;
    }
    
    public function getInitialWorkflowUrl($siteId=null)
    {
        if (is_null($siteId))
            $siteId = $this->page->site_id;
        $workflow = Workflow::model()->findByAttributes(array(
            'site_id'=>$siteId,
            'type'=>Workflow::TYPE_INITITAL,
        ));
        if (is_object($workflow))
            return $workflow->url;
        return '';
    }
}